module.exports = options => {
  const jwt = require('jsonwebtoken');
  const admin = require('../models/admin');
  const config = require('../config');

  return async (req, res, next) => {
    // 校验token
    const token = String(req.headers.authorization || '').split(' ').pop();
    if (!token) return next({ code: 403, msg: 'token不存在' })
    // assert(token, 401, '请先登录!');
    let id = ''
    jwt.verify(token, config.JWTSECRET, (err, decoded) => {
      if (err) return next({ code: 403, msg: 'token失效' })
      id = decoded.id
    });
    // assert(id, 401, '请先登录!');

    req.user = await admin.findByPk(id)
    if (!req.user) return next({ code: 403, msg: '用户不存在' })

    await next();
  }
};